<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.phone" placeholder="手机号" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-select v-model="listQuery.zid" placeholder="请选择分组" clearable style="width: 200px" class="filter-item">
                <el-option v-for="item in fzOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>

            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                查询
            </el-button>
            <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加号码
      </el-button> -->
            <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="alllogin">
                批量登陆
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="alltypes">
                批量检测
            </el-button>
            <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-upload2"
                @click="handleUpload">
                导入数据
            </el-button> -->
            <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                @click="handleDownload">
                导出数据
            </el-button>


        </div>
        <el-table :key="tableKey" ref="multipleTable" @selection-change="handleSelectionChange" v-loading="listLoading"
            :data="list" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                :class-name="getSortClass('id')">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="手机号" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.phone }}</span>
                </template>
            </el-table-column>

            <el-table-column label="分组" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.zname }}</span>
                </template>
            </el-table-column>

            <el-table-column label="详细数据" width="150px" align="center">
                <template slot-scope="{row}">
                    <el-popover trigger="hover" placement="top">
                        <p>消息私钥: {{ row.IdentityPriKey }}</p>
                        <p>消息公钥: {{ row.IdentityPubKey }}</p>
                        <p>静态私钥: {{ row.StaticPriKey }}</p>
                        <p>静态公钥: {{ row.StaticPubKey }}</p>
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">详细数据</el-tag>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="协议数据" width="150px" align="center">
                <template slot-scope="{row}">
                    <el-popover trigger="hover" placement="top">
                        <p>{{ row.jsonalls }}</p>
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">协议数据</el-tag>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="状态" class-name="status-col" width="100">
                <template slot-scope="{row}">
                    <el-tag :type="row.logonstatus | statusFilter">
                        {{ row.logonstatus == 1 ? '待核实' : row.logonstatus == 2 ? '登陆中' : row.logonstatus == 3 ? '登陆失败' :
                            row.logonstatus == 4 ? '待查询' : row.logonstatus == 5 ? '消息密钥异常' : '待核实' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="登陆失败次数" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.sbnum }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <!-- <el-button size="mini" type="success" @click="logins(row, 'published')">
                        登陆
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
                        删除
                    </el-button> -->
                    <el-button size="mini" type="primary" @click="getloglist(row, $index)">
                        登陆日志
                    </el-button>
                    <!-- <el-button size="mini" type="primary" plain @click="cp(row, $index)">
                        复制
                    </el-button> -->

                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
                <el-table-column label="手机号" width="150px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.phone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.content }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="json数据" width="250px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.jsonall }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="时间" width="150px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="impoleVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
                style="width: 400px; margin-left:50px;">
                <el-form-item label="分组" prop="username">
                    <el-select v-model="temp.zid" placeholder="请选择分组">
                        <el-option v-for="item in fzOptions" :key="item.id" :label="item.name" :value="item.id"
                            value-key="id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="导入账号">
                    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
                </el-form-item>
                <el-form-item label="账号" prop="phonelist">
                    <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 24 }" maxlength="40"
                        v-model="temp.phonelist" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="createData()">
                    导入数据
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, getDel, getLogin, getImplode, getLoginType, getFzList, getListAll } from '@/api/smsck'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
const statusOptions = [
    { key: 1, display_name: '授权' },
    { key: 2, display_name: '未授权' },
    { key: 3, display_name: '封禁' },
    { key: 4, display_name: '异常' }
]
export default {
    name: 'ComplexTable',
    components: { Pagination, UploadExcelComponent },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                1: 'info',
                2: 'success',
                3: 'danger'
            }
            return statusMap[status]
        },
        typeFilter(type) {
            return calendarTypeKeyValue[type]
        }
    },
    data() {
        return {
            tableKey: 0,
            list: null,
            listall: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 10,
                logonstatus: 2,
                phone: '',
                zid: ''
            },
            multipleSelection: [],
            statusOptions,
            showReviewer: false,
            temp: {
                id: undefined,
                listall: [],
                phonelist: '',
                zid: '',
            },
            fzOptions: [],
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: 'Edit',
                create: 'Create',
                getlist: 'GET',
                impolephone: 'Impole'
            },
            impoleVisible: false,
            dialogPvVisible: false,
            pvData: [],
            rules: {
                type: [{ required: true, message: 'type is required', trigger: 'change' }],
                // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
                title: [{ required: true, message: 'title is required', trigger: 'blur' }]
            },
            downloadLoading: false
        }
    },
    created() {
        this.getList()
        this.getFzListall()
        this.getlistall();
    },
    methods: {
        getFzListall() {
            getFzList().then(response => {
                console.log(response.data)
                this.fzOptions = response.data.list
            })
        },
        alllogin() {
            let list = this.multipleSelection
            let arr = []
            list.forEach(function (item, index) {
                console.log(item); //输出数组的每一个元素
                if (item.logonstatus != 2) {
                    arr.push(item.phone)
                }
            });
            if (arr.length > 0) {
                //进行登陆操作
                let temp = {
                    phone: arr.join(",")
                }
                this.listLoading = true
                getLogin(temp).then(response => {
                    this.$message({
                        message: '操作Success',
                        type: 'success'
                    })
                    this.getList();
                    this.listLoading = false
                })
            }
        },
        alltypes() {
            let list = this.multipleSelection
            let arr = []
            list.forEach(function (item, index) {
                console.log(item); //输出数组的每一个元素
                // if (item.logonstatus != 2) {
                arr.push(item.phone)
                // }
            });
            if (arr.length > 0) {
                //进行登陆操作
                let temp = {
                    phone: arr.join(",")
                }
                this.listLoading = true
                getLoginType(temp).then(response => {
                    this.$message({
                        message: '操作Success',
                        type: 'success'
                    })
                    this.getList();
                    setTimeout(() => {
                        this.listLoading = false
                    }, 1.5 * 1000)
                })
            }
        },


        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log('导入数据', this.multipleSelection)
        },
        cp(row, index) {
            let inputDom = document.createElement('textarea') // js创建一个文本框
            document.body.appendChild(inputDom) //将文本框暂时创建到实例里面
            inputDom.value = row.jsonalls //将需要复制的内容赋值到创建的文本框中
            inputDom.select() //选中文本框中的内容
            inputDom.focus()
            document.execCommand('copy') //执行复制操作
            document.body.removeChild(inputDom) //最后移出
            this.$notify({
                title: 'Success',
                message: '复制完成',
                type: 'success',
                duration: 2000
            })
        },
        getList() {
            this.listLoading = true
            fetchList(this.listQuery).then(response => {
                console.log(response.data)
                this.list = response.data.list
                this.total = response.data.count
                // Just to simulate the time of the request
                this.listLoading = false
            })
        },
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        logins(row, status) {
            //进行登陆操作
            let temp = {
                phone: row.phone
            }
            this.listLoading = true
            getLogin(temp).then(() => {
                this.$message({
                    message: '操作Success',
                    type: 'success'
                })
                this.listLoading = false
            })
            // row.status = status
        },

        resetTemp() {
            this.temp = {
                id: undefined,
                importance: 1,
                remark: '',
                timestamp: new Date(),
                title: '',
                status: 'published',
                type: ''
            }
        },

        getloglist(row, index) {
            //查询数据
            fetchPv({ phone: row.phone, types: 1 }).then(response => {
                console.log(response)
                this.pvData = response.data.list
            })
            this.dialogStatus = 'getlist'
            this.dialogFormVisible = true
        },
        handleUpload() {
            this.dialogStatus = 'impolephone'
            this.impoleVisible = true
        },
        beforeUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1
            if (isLt1M) {
                return true
            }
            this.$message({
                message: 'Please do not upload files larger than 1m in size.',
                type: 'warning'
            })
            return false
        },
        handleSuccess({ results, header }) {
            console.log(results)
            console.log(header)
            this.temp.listall = results
            let listall = results
            let arr = []
            listall.forEach(function (item, index) {
                arr.push(item.账号)
            });
            let arrs = arr.join(",");
            console.log(arrs);
            //输出数组的每一个元素
            this.temp.phonelist = arrs

        },
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    getImplode(this.temp).then(response => {
                        this.$notify({
                            title: 'Success',
                            message: '导入完成',
                            type: 'success',
                            duration: 2000
                        })
                        this.dialogFormVisible = false
                        // this.getList()
                    })
                }
            })
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row) // copy obj
            this.temp.timestamp = new Date(this.temp.timestamp)
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const tempData = Object.assign({}, this.temp)
                    updateArticle(tempData).then(() => {
                        const index = this.list.findIndex(v => v.id === this.temp.id)
                        this.list.splice(index, 1, this.temp)
                        this.dialogFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Update Successfully',
                            type: 'success',
                            duration: 2000
                        })
                    })
                }
            })
        },
        handleDelete(row, index) {
            let temp = {
                phone: row.phone
            }
            getDel(temp).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Created Successfully',
                    type: 'success',
                    duration: 2000
                })
            })
            this.list.splice(index, 1)
        },

        handleDownload() {
            this.downloadLoading = true
            import('@/vendor/Export2Excel').then(excel => {
                const tHeader = ['号码', '密钥']
                const filterVal = ['phone', 'tokens']
                const data = this.formatJson(filterVal)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: '在线账号'
                })
                this.downloadLoading = false
            })
        },
        formatJson(filterVal) {
            return this.listall.map(v => filterVal.map(j => {
                return v[j]
            }))
        },
        getlistall() {
            getListAll({ logonstatus: 2 }).then(response => {
                this.listall = response.data.list
                console.log(response.data.list)
            })
        },



        getSortClass: function (key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
